package net.siufung.web.xss.config;

import cn.hutool.core.util.ArrayUtil;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import net.siufung.core.utils.StringPool;
import net.siufung.web.xss.XssConstants;
import net.siufung.web.xss.XssFilter;
import net.siufung.web.xss.properties.XssProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.DispatcherType;
import java.util.Map;

/**
 * @author 陈建峰
 * @date 2022/10/13 5:56 下午
 * @since V1.0.0
 */
@Configuration
@EnableConfigurationProperties({XssProperties.class})
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@AllArgsConstructor
public class XssAutoConfig {

    private final XssProperties xssProperties;

    @Bean
    public FilterRegistrationBean<XssFilter> xssFilterRegistrationBean() {
        FilterRegistrationBean<XssFilter> registration = new FilterRegistrationBean<>();
        registration.setDispatcherTypes(DispatcherType.REQUEST);
        registration.setFilter(new XssFilter());
        String[] urlPatterns = xssProperties.getUrlPatterns();
        if(ArrayUtil.isEmpty(urlPatterns)){
            urlPatterns = new String[]{"/**"};
        }
        registration.setUrlPatterns(Lists.newArrayList(urlPatterns));
        registration.setName("XssFilter");
        registration.setOrder(Integer.MAX_VALUE);
        registration.setEnabled(xssProperties.getEnabled());
        Map<String, String> initParameters = Maps.newHashMap();
        if(ArrayUtil.isNotEmpty(xssProperties.getExcludeUrls())){
            initParameters.put(XssConstants.EXCLUDE_URLS,
                    Joiner.on(StringPool.COMMA).join(xssProperties.getExcludeUrls()));
        }
        registration.setInitParameters(initParameters);
        return registration;
    }



}
